<?php
/*
* @Name:    function.php
* @Version: 3.0
* @Update:  2013.1.30
* @Use:     Functions.
* @Author:  CoderChao
*/


// Function get_csv_files to read all the csv files (*.csv) at the same directory
function get_csv_files($dir) {
    $files = array();

    if (!is_dir($dir)) {
        return $files;
    }
    $d = dir($dir);
    while (false !== ($file = $d->read())) {
        if ($file != '.' && $file != '..') {
            $filename = $file;
            if(is_file($filename) && (substr($filename,-3) == 'csv')) 
            {
                $files[] = $filename;
            }else {
                $files = array_merge($files, get_csv_files($filename));
            }
        }
    }
    $d->close();
    return $files;
}


// Function get_keywords_array to read csv files keywors as an array
function get_keywords_array($directory,$is_home)
{
    $KeywordsArray = array();

    //Get all the CSV files
        $csvfilenames = get_csv_files($directory);
        $csv_file_names = implode($csvfilenames, "\n");
    
    if ( $is_home == 'home' )
    {
        shuffle($csvfilenames);
        $csvfilenames = array ($csvfilenames[0]);   //Only get 1 random csv file for homepage
    }
    

    //handle csv files
    foreach ($csvfilenames as $csvfile) 
    {
        $line = 0;
        $fp = fopen("$csvfile",'r');
        while ($keywords = fgetcsv ($fp,1000,',')) 
        {
            //skip line 1 for no keywords
            if($line == 0) 
            {
            $line++;
            //check if it is 'AdGroup' ,really keywords starts from line 2
            $AdGroupCheck = (($keywords['0']=='Ad Group')?'1':'0');
            continue;
            }
            elseif($line == 1) 
            {
            $line++;
            continue;
            }
            //Get the KeywordsArray 
            if( stripos($keywords[$AdGroupCheck],'free') === false && trim($keywords[$AdGroupCheck]) )
            {
            $KeywordsArray[]  = clean_keyword($keywords[$AdGroupCheck]);
            }
        }
    }
	return array_flip(array_flip($KeywordsArray));
}

//Clean the keywords
function clean_keyword($keyword)
{
    $clean_keyword = '';
    $search  = array('/',"'",'&',' ');
    $replace = array('-','','','-');
    $clean_keyword = str_replace($search, $replace, $keyword);
    return $clean_keyword;

}

//Get UCwords and with space seperte
function title_words($keyword)
{
    return ucwords(str_replace('-',' ',$keyword));
}

//Curl File Get Contents Function
function curl_file_get_contents($url)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10");
  curl_setopt($ch, CURLOPT_REFERER,'http://www.amazon.com/gp/aw/h.html');
  $output = curl_exec($ch);
  curl_close($ch);
   return $output;
}

//Get content from A9 result with given keyword
function get_a9_content($keyword,$TagID)
{
    $body = '';
    /*  Join the URL    */
    $keyword  = rawurlencode($keyword);    //rawurlencod can convert space into '%20'
    $search   = 'http://www.amazon.com/gp/aw/s/?page='.rand(2,5).'&ie=UTF8&k=';
    $url      = $search.$keyword;

    /*  Get Body Area   */
    $html     = curl_file_get_contents($url);    //Use Curl to get Original Search Result HTML Source Contents

    if (strstr($html, 'sorry') )  //No search results
    {
        $body = '<br /><br />Uh Oh! We are sorry. <br /><br />We know you are finding something about <br /><br /><h2>'.ucwords(str_replace('%20', ' ', $keyword)).'</h2><br />But We cannot find any matches products on <a href="http://www.amazon.com/?tag=homepage20-20" rel="nofollow">Amazon.com</a> for your search term.';
    }
    else
    {
        $body = explode('<div id="results">', $html);  //Seperate the HTML from '<div id="results">'
        $body = explode('<table class="paginationLinks">', $body[1]); //Get the core html code
        $body = str_replace(array(PHP_EOL,'<span class="smartMedium">Eligible for FREE Super Saver Shipping.</span>'), " ", $body[0]);    //Fix break line bug
        $body = '<br /><div id="results">'.trim($body);    //Get the Core Body Area

    /*  Replace Product URL    */
    $pattern  = '/\/gp\/aw\/d\/(\w+)\/([^>]*)>/';
    $body     = preg_replace($pattern, "http://www.amazon.com/dp/$1/?tag=$TagID\" rel=\"nofollow\">", $body);   //Replace
    }   //End of else part

    return $body;
}

//Get Express Content
function get_express_content($keyword)
{
    $body = '';
    /*  Join the URL    */
    $keyword  = rawurlencode($keyword);    //rawurlencod can convert space into '%20'
    $search   = 'http://m.aliexpress.com/search.htm?page='.rand(2,5).'&keywords=';
    $url      = $search.$keyword;

    /*  Get Body Area   */
    $html   = curl_file_get_contents($url);

    if (strstr($html, '<span class="f_o">0</span> Results') )  //No search results
    {
        $body = '<br /><br />Oh,No!Something must be wrong.<br /><br />We are also finding something like <br /><br /><h2>'.ucwords(str_replace('%20', ' ', $keyword)).'</h2><br />But right now , We still not find anything here. <br /><br />Give us some more time, I think we will do better when you come next time .';
    }
    else
    {
        $body = explode('<ul id="product-list">', $html);
        $body = explode('<div class="page">', $body[1]);
        $body = preg_replace('#<a([^>]*)>#', '<a>', $body[0]);
        $body = '<br /><ul id="product-list">'.$body;
    }

    return $body;
}

//Get Amazon Suggest Keywords
function get_amazon_keywords($keyword)
{
    $SuggestKeyword = '';

    /*  Add not more than 10 Related Keywords Links */
    $Suggests = 'http://completion.amazon.com/search/complete?search-alias=aps&mkt=1&q=';
    $AmazonUrl= $Suggests.urlencode($keyword);
    $json     = file_get_contents($AmazonUrl);
    $jsonArray = json_decode($json);
    $AmazonKeywords = $jsonArray[1];
    foreach ($AmazonKeywords as $AmazonKeyword) {
            $SuggestKeyword .='<a href="http://'.$_SERVER['SERVER_NAME'].'/'.clean_keyword($AmazonKeyword).'.html" title="'.ucwords($AmazonKeyword).'">'.ucwords($AmazonKeyword)."</a>";
    }
    return $SuggestKeyword;
}

//Get Google Suggest Keywords
function get_suggest_keywords($keyword)
{
    $GuideKeyword = '';
    /*  Add not more than 5 Related Keywords Links */
    $Suggests = 'http://google.com/complete/search?output=toolbar&q=';
    $GURL     = $Suggests.$keyword;
    $xml      = simplexml_load_file("$GURL");
    foreach ($xml->CompleteSuggestion as $Suggest) {
            $RelatedKeyword[] = $Suggest->suggestion['data'];
        }
    for ($i=1; $i<6; $i++) { 
        if (!empty($RelatedKeyword[$i-1])) {
            $GuideKeyword .='<a href="http://'.$_SERVER['SERVER_NAME'].'/'.clean_keyword($RelatedKeyword[$i-1]).'.html" title="'.ucwords($RelatedKeyword[$i-1]).'">'.ucwords($RelatedKeyword[$i-1])."</a>";
        }
    }
    return $GuideKeyword;

}

//Get last 5 Google Suggest Keywords
function get_last_suggest_keywords($keyword)
{
    $GuideKeyword = '';
    /*  Add last 5 Related Keywords Links */
    $Suggests = 'http://google.com/complete/search?output=toolbar&q=';
    $GURL     = $Suggests.$keyword;
    $xml      = simplexml_load_file("$GURL");
    foreach ($xml->CompleteSuggestion as $Suggest) {
            $RelatedKeyword[] = $Suggest->suggestion['data'];
        }
    for ($i=6; $i<10; $i++) { 
        if (!empty($RelatedKeyword[$i-1])) {
            $GuideKeyword .='<a href="http://'.$_SERVER['SERVER_NAME'].'/express/'.clean_keyword($RelatedKeyword[$i-1]).'.html" title="'.ucwords($RelatedKeyword[$i-1]).'">'.ucwords($RelatedKeyword[$i-1])."</a>";
        }
    }
    return $GuideKeyword;

}

//Clear html space
function compress_html($string)
{   // Thanks for anymous who code this function
    $string = str_replace("\r\n", '', $string);  
    $string = str_replace("\n", '', $string);  
    $string = str_replace("\t", '', $string);  
    $pattern = array (  
                    "/> *([^ ]*) *</",  
                    "/[\s]+/",  
                    "/<!--[^!]*-->/",  
                    "/\" /",  
                    "/ \"/",  
                    "'/\*[^*]*\*/'" 
                    );  
    $replace = array (  
                    ">\\1<",  
                    " ",  
                    "",  
                    "\"",  
                    "\"",  
                    "" 
                    );  
    return preg_replace($pattern, $replace, $string);  
}

?>